package com.acme.superchat.service.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.rmi.UnknownHostException;

/**
 * @author Alexander Kotov (kotov.alex.22@gmail.com)
 */
public class Client {
    private final int port;
    private final String connection;

    public Client(String connection, int port) {
        this.port = port;
        this.connection = connection;
    }

    private void sendMessage(final PrintWriter out, final String message) {
        out.println(message);
        //System.out.println(new Date().toString() + " " + message);
    }

    private void processConsoleInput(final PrintWriter out) {
        String consoleInput;
        try (BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {
            while ((consoleInput = stdIn.readLine()) != null) {
                sendMessage(out, consoleInput);
            }
        } catch (IOException ioException) {
            ioException.getStackTrace();
            System.err.println(ioException.getMessage());
        }
    }

    public void run() {
        try (Socket socket = new Socket(connection, port);
             PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
            System.out.println("Connection was established!");
            new Thread(new ClientMessageReceiver(input, Thread.currentThread())).start();
            processConsoleInput(output);

        } catch (UnknownHostException unknownHostException) {
            //unknownHostException.printStackTrace();
            System.err.println("Connection to unknown host failed");
        } catch (IOException ioException) {
            //ioException.printStackTrace();
            //System.err.println(ioException.getMessage());
            System.err.println("Connection failed!");
        } catch (NullPointerException nullPointerException) {
            nullPointerException.printStackTrace();
            System.err.println(nullPointerException.getMessage());
        }
    }
}